export default {
  uploadFile(path, opts) {
    const {
      url = uni.$apiHub.uploadFile,
      name = "file",
      onStart,
      onUpdate,
      ...config
    } = opts;
    return new Promise((resolve, fail) => {
      const task = uni.uploadFile({
        url,
        filePath: path,
        name,
        ...config,
        success(res) {
          let { data } = res;
          if (typeof data == "string") {
            try {
              data = JSON.parse(data);
            } catch (error) {
              data = { url: "" };
            }
          }
          if (Array.isArray(data)) data = data[0];
          resolve(data);
        },
        fail,
      });
      // https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/UploadTask.onProgressUpdate.html
      task.onProgressUpdate((res) => {
        if (onUpdate) onUpdate(res);
      });
      if (onStart) {
        onStart(task);
      }
    });
  },
};
